package com.maltys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maltys.dao.UserMapper;
import com.maltys.domain.entity.User;
import com.maltys.service.IUserService;
import com.maltys.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author malty
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public UserDetails getUserByUsername(String username) {
        return this.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @Override
    public User registerUser(User user) {
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);
        boolean save = this.save(user);
        if (Boolean.FALSE.equals(save)) {
            throw new RuntimeException("注册失败");
        }
        User registry = this.getById(user.getId());
        registry.setPassword(null);
        return registry;
    }

    @Override
    public String login(User user) {
        User userDb = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (ObjectUtils.isEmpty(userDb)) {
            return "";
        }

        if (passwordEncoder.matches(user.getPassword(), userDb.getPassword())) {
            return jwtTokenUtil.generateToken(user);
        }
        return "";
    }

    @Override
    public User queryByUserName(String userName) {
        return this.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, userName));
    }
}
